FakeServer.php

<?php

namespace Tlf\Tester;

/**
 * Used to run a php script as if an HTTP request had been made.
 */
class FakeServer {


    /**
     * Set up the $_SERVER, $_GET, and $_POST global variables accordingly, require the $deliver_file, and return its output. 
     */
    public function send_request(string $deliver_file, string $url, string $method = "GET", array $params = []): string {
        $orig_server = $_SERVER;
        $orig_GET = $_GET;
        $orig_POST = $_POST;

        try {
            // @todo support adding get params to uri
            $_SERVER['REQUEST_URI'] = $url;
            if ($method == "GET") $_GET = $params;
            else if ($method=="POST") $_POST = $params;

            ob_start();
            require($deliver_file);
            $output = ob_get_clean();

        } catch (\Exception $e){

            $_SERVER = $orig_server;
            $_GET = $orig_GET;
            $_POST = $orig_POST;
            throw $e;
        }

        $_SERVER = $orig_server;
        $_GET = $orig_GET;
        $_POST = $orig_POST;

        return $output;

    }

}